<template>
    <div class="category-container">
        <el-card class="category-card">
            <template #header>
                <div class="card-header">
                    <span>课程类别管理</span>
                    <el-button type="primary" size="small" @click="handleAdd">新增类别</el-button>
                </div>
            </template>

            <el-table :data="categoryList" border style="width: 100%">
                <el-table-column label="序号" width="80">
                    <template #default="scope">
                        {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="类别名称" />
                <el-table-column prop="description" label="描述" />
                <el-table-column prop="courseCount" label="课程数量" width="120" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                class="pagination"
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="fetchCategoryData"
                @current-change="fetchCategoryData"
            />
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form :model="form" label-width="80px">
                <el-form-item label="类别名称">
                    <el-input v-model="form.name" placeholder="请输入类别名称" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import requestUtil from '@/util/request.js'


let courseAllCache = null
const fetchAllCourses = async () => {
    if (courseAllCache) {
        return courseAllCache
    }

    try {
        const res = await requestUtil.get('/program/msg')
        courseAllCache = res.data.data || []
        return courseAllCache
    } catch (error) {
        console.error('获取课程数据失败:', error)
        return []
    }
}
// 表格数据
const categoryList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = ref({
    id: null,
    name: '',
    description: ''
})

// 获取类别数据
const fetchCategoryData = async () => {
    try {
        const res = await requestUtil.get('/category/msg', {
            params: {
                page: currentPage.value,
                page_size: pageSize.value
            }
        })
       // 获取每个类别的课程数量
        const listWithCourseCount = await Promise.all(
            res.data.data.map(async (category) => {
                const count = await fetchCourseCountByCategoryId(category.category_id)
                return {
                    ...category,
                    courseCount: count
                }
            })
        )

        categoryList.value = listWithCourseCount
        total.value = res.data.total
    } catch (error) {
        console.error('获取类别数据失败:', error)
    }
}
// 获取指定类别 ID 的课程数量
const fetchCourseCountByCategoryId = async (category_id) => {

        const courseAll = await fetchAllCourses()
        // 现在可以直接使用 course.category_id 进行比较
        const filteredCourses = courseAll.filter(course => course.category_id === Number(category_id))
        return filteredCourses.length

  }


// 新增类别
const handleAdd = () => {
    dialogTitle.value = '新增课程类别'
    form.value = { id: null, name: '', description: '' }
    dialogVisible.value = true
}

// 编辑类别
const handleEdit = (row) => {
    dialogTitle.value = '编辑课程类别'
    form.value = { ...row }
    dialogVisible.value = true
}

// 删除类别
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除【${row.name}】类别吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await requestUtil.del(`/category/delete/${row.category_id}`)
            ElMessage.success('删除成功')
            await fetchCategoryData()
        } catch (error) {
            console.error('删除失败:', error)
        }
    }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
    try {
        // 从本地存储获取用户ID
        const userId = localStorage.getItem('user_id')

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期，请重新登录')
          return
        }
        if (form.value.category_id) {
            // 编辑
            await requestUtil.put(`/category/update/${form.value.category_id}`,{
                name: form.value.name,
                description: form.value.description,
            })
            ElMessage.success('更新成功')
        } else {
            // 新增
            await requestUtil.post('/category/add',{
                name: form.value.name,
                description: form.value.description,
                create_by_id: userId
            } )
            ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        await fetchCategoryData()
    } catch (error) {
        console.error('操作失败:', error)
    }
}

onMounted(() => {
    fetchCategoryData()
})
</script>

<style lang="scss" scoped>
.category-container {
    padding: 20px 0;

    .category-card {
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;
        }
    }

    .pagination {
        margin-top: 20px;
        justify-content: flex-end;
    }
}
</style>